package com.huawen.cms.app.util;

import com.alibaba.fastjson.JSON;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

@WebFilter(filterName = "CheckLoginFilter", urlPatterns = "/home/*")
public class CheckLoginFilter implements Filter {

    private static final Set<String> ALLOWED_PATHS = Collections.unmodifiableSet(new HashSet<>(
            Arrays.asList("/home/index", "/home/login","*")));

    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        String path = request.getRequestURI().substring(request.getContextPath().length()).replaceAll("[/]+$", "");
        boolean allowedPath = ALLOWED_PATHS.contains(path);

        //判断是否为ajax请求，默认不是
        boolean isAjaxRequest = false;
        if (!StringUtils.isEmpty(request.getHeader("x-requested-with")) && request.getHeader("x-requested-with").equals("XMLHttpRequest")) {
            isAjaxRequest = true;
        }

        if (allowedPath) {
            System.out.println("这里是不需要处理的url进入的方法");
            chain.doFilter(req, res);
        } else {

            System.out.println("这里是需要处理的url进入的方法");

            if (isAjaxRequest) {
                CommonResult comResult = new CommonResult();
                comResult.setMsg("no authorize");
                comResult.setSuccess(false);
                comResult.setCode(-1000);

                //把返回值输出到客户端
                ServletOutputStream out = response.getOutputStream();
                String jsonString = JSON.toJSONString(comResult);

                out.write(jsonString.getBytes());
                out.flush();
            } else {
                response.sendRedirect(request.getContextPath() + "/home/login");
                //如果同步登陆后台就加returnUrl
            }
        }
    }


    @Override
    public void init(FilterConfig arg0) throws ServletException {

    }

}
